package array;

public class MaxLengthOfGivenSum {

	public static void main(String[] args) {
		int[] array = { 1, 3, 0, 5, 4, 3, 9, 1, 1, 1, 1, 2, 3 };
		// int[] array1 = {3,4,2,0,0,1};
		int[] array1 = { 13, 12, 15, 14, 17 };
		// int[] array1 = {1,1,1,1,100,1,1};
		// System.out.println(getLength(array, 9));
		System.out.println(getLength(array, 9));
		System.out.println(getLength(array1, 9));
	}
	/**
	 * 只针对正数序列
	 * @param array 正数序列(contain 0)
	 * @param givenSum
	 * @return
	 */
	public static int getLength(int[] array, int givenSum){
		if(array == null || array.length <= 0){
			System.err.println("您输入的数据有误");
			return -1;
		}
		//使用双指针解决,小于等于givenSum时，right++，大于时left++
		int left = 0, right = 0;  
		int maxlength = 0, currentSum = array[0];
		while ( right < array.length) {
			System.out.println("CurrentSum" + currentSum + "left" + left + "right" + right);
			if(currentSum == givenSum ){
				maxlength = Math.max(maxlength, right - left + 1);
				right++;
				if (right == array.length) {
					break;
				}
				currentSum += array[right];
			}else if(currentSum <= givenSum){
				right++;
				if (right == array.length) {
					break;
				}
				currentSum += array[right];
			}else {
				currentSum -= array[left++];
			}
//			if(left > right){
//				System.err.println("没有找到");
//				return 0;
//			}
		}
		return maxlength;
	}
}
